package com.websocket.example.listener;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.concurrent.CountDownLatch;


@Configuration
public class RedisMessageListenerConfiguration {

    /**
     * @param connectionFactory
     * @param listenerAdapter1
     * @param listenerAdapter2
     * @param listenerAdapter3
     * @return: org.springframework.data.redis.listener.RedisMessageListenerContainer
     * @decription 创建链接工厂
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter1,
                                                   MessageListenerAdapter listenerAdapter2,
                                                   MessageListenerAdapter listenerAdapter3) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        //（不同的监听器可以收到同一个频道的信息）接受消息的频道
        container.addMessageListener(listenerAdapter1, new PatternTopic("socket-1"));

        container.addMessageListener(listenerAdapter2, new PatternTopic("socket-1"));

        container.addMessageListener(listenerAdapter3, new PatternTopic("socket-1"));
        return container;
    }


    /**
     * 绑定消息监听者和接收监听的方法
     *
     * @param receiver
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter1(ReceiverRedisMessageListener receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage1");
    }

    /**
     * 绑定消息监听者和接收监听的方法
     *
     * @param receiver
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter2(ReceiverRedisMessageListener receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage2");
    }

    /**
     * 绑定消息监听者和接收监听的方法
     *
     * @param receiver
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter3(ReceiverRedisMessageListener receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage3");
    }

    /**
     * 注册订阅者
     *
     * @param latch
     * @return
     */
    @Bean
    ReceiverRedisMessageListener receiver(CountDownLatch latch) {
        return new ReceiverRedisMessageListener(latch);
    }


    /**
     * 计数器，用来控制线程
     *
     * @return
     */
    @Bean
    public CountDownLatch latch() {
        return new CountDownLatch(1); //指定了计数的次数 1
    }
}